package com.xwb.controller;


import com.fasterxml.jackson.annotation.JsonProperty;
import com.xwb.dao.WorkDao;
import com.xwb.domain.Work;
import com.xwb.service.WorkService;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@NoArgsConstructor
@Data
@RestController
@RequestMapping("/works")
@PreAuthorize("hasAuthority('system:dept:work')")
public class WorkController {
    @Autowired
    private WorkDao workDao;
    @Autowired
    private WorkService workService;

    @JsonProperty("competitionId")
    private String competitionId;
    @JsonProperty("teamNumber")
    private String teamNumber;
    @JsonProperty("preliminaryType")
    private String preliminaryType;
    @JsonProperty("preliminaryWork")
    private String preliminaryWork;
    @JsonProperty("preliminarySubmitDate")
    private String preliminarySubmitDate;
    @JsonProperty("preliminaryMark")
    private String preliminaryMark;
    @JsonProperty("finalType")
    private Object finalType;
    @JsonProperty("finalWork")
    private Object finalWork;
    @JsonProperty("finalSubmitDate")
    private Object finalSubmitDate;
    @JsonProperty("finalMark")
    private Object finalMark;

    /**
     * 该方法用于保存work表的信息
     */
    @PostMapping
    public Result saveWork(@RequestBody Work work) {
        boolean flag = workService.saveWork(work);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
    }

    /**
     * 该方法根据初赛成绩和排名筛选出进入决赛的名单
     */
    @GetMapping("/{enteringRank}")
    public Result showWork(@PathVariable Integer enteringRank) {
        List<String> list = workDao.selectEnteringFinal();
        /**
         * 查询work表中的entering_final字段是否有值，有的话全部设置成null
         */
        if (list != null) {
            workDao.setEnteringFinalNull();
        }
        workDao.updateEliminator();
        //更新出进入决赛的排名
        workDao.updateFinaList(enteringRank);
        //将没有进入决赛的enteringFinal设置成out
        List<Work> works = workDao.showAllWork();

        Integer code = works != null ? Code.GET_OK : Code.GET_ERR;
        String msg = works != null ? "" : "数据查询失败，请重试";
        return new Result(code, works, msg);
    }

    /**
     * 该方法用于展示所有进入决赛的队伍
     */
    @PostMapping("/showFinalists")
    public Result showFinalists() {
        List<Work> works = workService.showFinalist();
        Integer code = works != null ? Code.GET_OK : Code.GET_ERR;
        String msg = works != null ? "获取决赛队伍数据成功" : "数据查询失败，请重试";
        return new Result(code, works, msg);
    }
}
